<template>
  <div class="inventory-management">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="库存管理"
      left-text="返回"
      right-text="新增"
      left-arrow
      @click-left="$router.back()"
      @click-right="showAddDialog = true"
      fixed
      placeholder
      safe-area-inset-top
      class="custom-nav-bar"
    />
    
    <!-- 搜索框 -->
    <van-search
      v-model="searchQuery"
      placeholder="请输入产品名称或位置搜索"
      @search="fetchInventory"
      shape="round"
      background="#f7f8fa"
      class="custom-search"
    />
    
    <!-- 列表区域 -->
    <van-pull-refresh 
      v-model="refreshing" 
      @refresh="onRefresh"
      success-text="刷新成功"
      class="custom-refresh"
    >
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多数据了"
        @load="fetchInventory"
        class="custom-list"
      >
        <!-- 库存卡片 -->
        <div 
          v-for="item in inventoryList" 
          :key="item.inventoryId"
          class="inventory-card"
        >
          <van-swipe-cell>
            <van-cell-group inset>
              <van-cell 
                :title="`产品名称: ${item.productId}`" 
                :value="`数量: ${item.quantity}`"
                :label="`位置: ${item.location}`"
                class="custom-cell"
              >
                <template #extra>
                  <van-tag 
                    :color="item.quantity > 10 ? '#7232dd' : '#ee0a24'" 
                    plain
                  >
                    {{ item.quantity > 10 ? '充足' : '紧缺' }}
                  </van-tag>
                </template>
              </van-cell>
              <van-cell 
                title="更新时间" 
                :value="formatTime(item.updateTime)" 
                class="custom-cell time-cell"
              />
            </van-cell-group>
            
            <template #right>
              <van-button 
                square 
                type="primary" 
                text="编辑" 
                @click="handleEdit(item)"
                class="swipe-button"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </van-pull-refresh>
    
    <!-- 新增库存弹窗 -->
    <van-dialog
    v-model:show="showAddDialog"
    title="新增库存"
    show-cancel-button
    @confirm="handleAdd"
    class="custom-dialog"
  >
    <van-form @submit="handleAdd">
      <van-field
        v-model="newInventory.productId"
        label="产品名称"
        placeholder="请输入产品名称"
        type="number"
        :rules="[{ required: true, message: '请输入产品名称' }]"
        class="custom-field"
      />
      <van-field
        v-model="newInventory.quantity"
        label="库存数量"
        placeholder="请输入库存数量"
        type="number"
        :rules="[{ required: true, message: '请输入库存数量' }]"
        class="custom-field"
      />
      <van-field
        v-model="newInventory.location"
        is-link
        readonly
        label="仓库位置"
        placeholder="请选择仓库位置"
        @click="showLocationPicker = true"
        :rules="[{ required: true, message: '请选择仓库位置' }]"
        class="custom-field"
      />
    </van-form>
  </van-dialog>
    
    <!-- 编辑库存弹窗 -->
    <van-dialog
      v-model:show="showEditDialog"
      title="编辑库存"
      show-cancel-button
      @confirm="handleUpdate"
      class="custom-dialog"
    >
      <van-form @submit="handleUpdate">
        <van-field
          v-model="currentInventory.productId"
          label="产品名称"
          placeholder="请输入产品名称"
          type="number"
          :rules="[{ required: true, message: '请输入产品名称' }]"
          class="custom-field"
        />
        <van-field
          v-model="currentInventory.quantity"
          label="库存数量"
          placeholder="请输入库存数量"
          type="number"
          :rules="[{ required: true, message: '请输入库存数量' }]"
          class="custom-field"
        />
        <van-field
        v-model="currentInventory.location"
        is-link
        readonly
        label="仓库位置"
        placeholder="请选择仓库位置"
        @click="showLocationPicker = true"
        :rules="[{ required: true, message: '请选择仓库位置' }]"
        class="custom-field"
      />
      </van-form>
    </van-dialog>
    
    <!-- 仓库位置选择器 -->
    <van-popup v-model:show="showLocationPicker" position="bottom">
      <van-picker
  :columns="locationOptions"
  @confirm="onLocationConfirm"
  @cancel="showLocationPicker = false"
  :value-key="locationOptions[0]?.text ? 'text' : undefined"
/>
  </van-popup>
    
    <!-- 悬浮添加按钮 -->
    <van-floating-bubble
      v-model:offset="offset"
      axis="xy"
      magnetic="x"
      @click="showAddDialog = true"
      class="floating-add-btn"
    >
      <van-icon name="plus" size="24" />
    </van-floating-bubble>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Toast } from 'vant';
import axios from 'axios';

// 库存列表数据
const inventoryList = ref([]);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = 10;

// 仓库位置数据
const locationOptions = ref([]);
const showLocationPicker = ref(false);

// 新增库存相关
const showAddDialog = ref(false);
const newInventory = ref({
  productId: '',
  quantity: '',
  location: '',
  createBy: 1 // 假设当前用户ID为1
});
const offset = ref({ x: 0, y: 0 });

// 编辑库存相关
const showEditDialog = ref(false);
const currentInventory = ref({
  inventoryId: '',
  productId: '',
  quantity: '',
  location: '',
  updateBy: 1 // 假设当前用户ID为1
});

// 格式化时间显示
const formatTime = (time) => {
  const date = new Date(time);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
};

// 获取仓库位置数据
const fetchLocations = async () => {
  try {
    const response = await axios.get('/api/mobile/locations');
    
    // 安全处理响应数据
    const locations = JSON.parse(JSON.stringify(response.data.data)) || [];
    
    // 确保是平面数组
    locationOptions.value = response.data.data.map(item => ({
  text: item.name || item, // 兼容字符串和对象
  value: item.id || item   // 可选的值字段
}));
    
  } catch (error) {
    console.error('获取仓库位置失败:', error);
    Toast.fail('获取仓库位置失败');
  }
};

// 获取库存列表
const fetchInventory = async () => {
  try {
    loading.value = true;
    
    const params = {
      page: currentPage.value,
      pageSize,
    };

    if (/^\d+$/.test(searchQuery.value)) {
      params.productId = parseInt(searchQuery.value);
    } else {
      params.search = searchQuery.value;
    }

    const response = await axios.get('/api/mobile/select', { params });
    const data = response.data.data;
    
    if (refreshing.value) {
      inventoryList.value = data.list;
    } else {
      inventoryList.value = [...inventoryList.value, ...data.list];
    }

    finished.value = data.list.length < pageSize;
    loading.value = false;
    refreshing.value = false;
  } catch (error) {
    Toast.fail('加载失败');
    loading.value = false;
  }
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  currentPage.value = 1;
  fetchInventory();
};

// 修改后的位置选择处理
const onLocationConfirm = (value) => {
  console.log('选择的值:', value); // 调试用
  
  // 处理不同格式的返回值
  let selectedValue;
  if (Array.isArray(value)) {
    selectedValue = value[0]; // 多列选择器情况
  } else if (value?.selectedValues) {
    selectedValue = value.selectedValues[0];
  } else {
    selectedValue = value;
  }

  // 赋值给对应的表单
  const target = showAddDialog.value 
    ? newInventory.value 
    : currentInventory.value;
  
  target.location = String(selectedValue); // 确保是字符串
  showLocationPicker.value = false;
};

// 新增库存
const handleAdd = async () => {
  try {
    const response = await axios.post('/api/mobile/insert', newInventory.value);
    if (response.data.success) {
      Toast.success('新增库存成功');
      showAddDialog.value = false;
      newInventory.value = {
        productId: '',
        quantity: '',
        location: '',
        createBy: 1
      };
      refreshing.value = true;
      fetchInventory();
    }
  } catch (error) {
    console.error('新增库存失败:', error);
    Toast.fail('新增库存失败');
  }
};

// 编辑库存
const handleEdit = (item) => {
  currentInventory.value = {
    inventoryId: item.inventoryId,
    productId: item.productId,
    quantity: item.quantity,
    location: String(item.location), // 强制转为字符串
    updateBy: 1
  };
  showEditDialog.value = true;
};

// 更新库存
const handleUpdate = async () => {
  try {
    const response = await axios.put(`/api/mobile/update/${currentInventory.value.inventoryId}`, currentInventory.value);
    if (response.data.success) {
      Toast.success('更新库存成功');
      showEditDialog.value = false;
      refreshing.value = true;
      fetchInventory();
    }
  } catch (error) {
    console.error('更新库存失败:', error);
    Toast.fail('更新库存失败');
  }
};

// 初始化加载数据
onMounted(() => {
  fetchInventory();
  fetchLocations();
});
</script>

<style scoped>
/* 原有样式保持不变 */
.inventory-management {
  --primary-color: #7232dd;
  --success-color: #07c160;
  --danger-color: #ee0a24;
  --warning-color: #ff976a;
  --text-color: #333;
  --border-color: #ebedf0;
  --background-color: #f7f8fa;
  --card-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  
  min-height: 100vh;
  background-color: var(--background-color);
  padding-bottom: 50px;
  color: var(--text-color);
}

.custom-nav-bar {
  background: linear-gradient(135deg, var(--primary-color) 0%, #a166ff 100%);
  color: white;
}

.custom-nav-bar :deep(.van-nav-bar__title),
.custom-nav-bar :deep(.van-nav-bar__text) {
  color: white;
}

.custom-nav-bar :deep(.van-icon) {
  color: white;
}

.custom-search {
  padding: 10px 16px;
}

.custom-search :deep(.van-search__content) {
  background-color: white;
}

.custom-refresh :deep(.van-pull-refresh__head) {
  color: var(--primary-color);
}

.custom-list {
  padding: 0 12px;
}

.inventory-card {
  margin: 10px 0;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: var(--card-shadow);
  transition: transform 0.2s;
}

.inventory-card:active {
  transform: scale(0.98);
}

.custom-cell {
  padding: 16px;
}

.custom-cell :deep(.van-cell__title) {
  font-weight: 500;
  flex: 2;
}

.custom-cell :deep(.van-cell__value) {
  flex: 3;
  text-align: right;
  color: var(--text-color);
}

.time-cell :deep(.van-cell__value) {
  color: #969799;
  font-size: 12px;
}

.swipe-button {
  height: 100%;
  border-radius: 0;
}

.custom-dialog :deep(.van-dialog__header) {
  font-size: 18px;
  font-weight: bold;
  padding-top: 20px;
}

.custom-dialog :deep(.van-dialog__content) {
  padding: 20px;
}

.custom-field :deep(.van-field__label) {
  width: 80px;
  color: var(--text-color);
}

.floating-add-btn {
  --floating-button-size: 56px;
  --floating-button-color: var(--primary-color);
  
  width: var(--floating-button-size);
  height: var(--floating-button-size);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

@media (max-width: 480px) {
  .custom-cell {
    padding: 12px;
  }
  
  .inventory-card {
    margin: 8px 0;
  }
}
</style>